package com.hiwhitley.chapter05;

import com.hiwhitley.easy.day23.ReverseBits_190;

/**
 * Created by hiwhitley on 17-1-16.
 */
public class RotateWord {

    public void rotateWord(char[] chars) {
        if (chars == null || chars.length == 0) {
            return;
        }

        reverse(chars, 0, chars.length - 1);
        int l = -1;
        int r = -1;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] != ' ') {
                l = i == 0 || chars[i - 1] == ' ' ? i : l;
                r = i == chars.length - 1 || chars[i + 1] == ' ' ? i : r;
            }

            if (l != -1 && r != -1) {
                reverse(chars, l, r);
                l = -1;
                r = -1;
            }
        }
        System.out.println(String.valueOf(chars));

    }

    public  void rotate1(char[] chars, int size) {
        if (chars == null || size <= 0 || size >= chars.length)
            return;
        reverse(chars, 0, size - 1);
        reverse(chars, size, chars.length - 1);
        reverse(chars, 0, chars.length - 1);
    }

    public void reverse(char[] chars, int start, int end) {
        char tmp = 0;
        while (start < end) {
            tmp = chars[start];
            chars[start] = chars[end];
            chars[end] = tmp;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
        RotateWord main = new RotateWord();
        String str = "pig love apple";
        main.rotateWord(str.toCharArray());
    }
}
